import router from '@ohos.router';
import prompt from '@ohos.prompt';
import data_storage from '@ohos.data.storage';
import GameStorageConstant from '../../../model/GameStorageConstant.js'
import ability_featureAbility from '@ohos.ability.featureAbility';

export default {
    data: {
        nickName: '',
        GameStorageConstant : new GameStorageConstant(),
        storage: null,
        isCentralDevice:true // 是否为中心设备
    },
    onInit() {
        console.info("GameStorageConstant:" + this.GameStorageConstant.KEY_NICK_NAME);
        let params = router.getParams();
        if (typeof(params) != 'undefined') {
            this.isCentralDevice = params.is_central_device;
        }
    },

    onNicknameChange(data) {
        console.info("nick name change:" + data.value);
        this.nickName = data.value;
    },

    onConfirm() {
        if (this.nickName.length < 0) {
            prompt.showToast({
               message: this.$t('strings.nick_name_null'),
                duration: 3000
            });
            return;
        }
        // todo 判断昵称是否已经存在
        console.info("confirm, go to setting")
        //  保存数据 跳转到设置页面
        this.saveNickName();
    },

    saveNickName() {
        var context = ability_featureAbility.getContext();
        let self = this;
        context.getFilesDir().then((path) => {
            console.info("[saveNickName] get the storage path successful. path:" + JSON.stringify(path));
            const myStoragePath = self.GameStorageConstant.LOCAL_STORAGE_PATH;
            let promiseSt = data_storage.getStorage(path + myStoragePath);
            promiseSt.then((storage) => {
                self.storage = storage;
                let promise  = storage.put(self.GameStorageConstant.KEY_NICK_NAME, self.nickName);
                promise.then(()=> {
                    console.info("[saveNickName] save nick name success");
                    storage.flushSync();
                    self.gotoSetting();
                }).catch((err) => {
                    console.error("[saveNickName] save nick name fail:" + err);
                    prompt.showToast({
                        message: this.$t('strings.nick_name_save_fail'),
                        duration: 3000
                    });
                });
            }).catch((err) => {
                console.error('[saveNickName] get the storage failed. err: ' + JSON.stringify(err));
            });
        }).catch((err) => {
            console.error('[saveNickName] getFilesDir get the storage failed. err: ' + JSON.stringify(err));
        });
    },

    gotoSetting() {
        router.replace({
            url : "pages/setting/setting",
            params:{
                nick_name: this.nickName,
                is_central_device: this.isCentralDevice
            }
        });
    }

}
